package com.example.demo.domain.entity;

import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.text.DecimalFormat;
import java.util.List;

/**
 * 主订单信息
 *
 * @author ouchengchang
 */
@Slf4j
@NoArgsConstructor
@Data
public class OrderInfo {

    /**
     * 订单总优惠金额
     */
    private Double totalDiscountAmount;

    /**
     * 配送费
     */
    private Double deliveryFee;

    /**
     * 订单明细列表
     */
    private List<OrderDetail> orderDetailList;

    /**
     * 订单总金额（原价）
     */
    private Double totalOrderAmount;

    public OrderInfo(Double totalDiscountAmount, Double deliveryFee, List<OrderDetail> orderDetailList) {
        log.info("初始化主订单信息");
        this.totalDiscountAmount = totalDiscountAmount;
        this.deliveryFee = deliveryFee;
        this.orderDetailList = orderDetailList;
    }

    /**
     * 计算订单总金额
     */
    public void calcTotalOrderAmount() {
        totalOrderAmount = orderDetailList.stream().mapToDouble(OrderDetail::getAmount).sum() + deliveryFee;
    }

    /**
     * 计算订单明细的优惠占比，优惠金额，实付金额
     */
    public void calcOrderDetailPayAmount() {
        orderDetailList.forEach(e -> e.calcPayAmount(totalOrderAmount, totalDiscountAmount));
    }

    /**
     * 输出主订单信息
     */
    public void displayOrderInfo() {
        log.info("订单明细:");
        for (OrderDetail orderDetail : orderDetailList) {
            log.info(" * 商品:{}，单价:{}", orderDetail.getName(), orderDetail.getAmount());
        }
        log.info("订单总优惠金额:{}", totalDiscountAmount);
        log.info("订单配送费:{}", deliveryFee);
        log.info("订单总金额:{}", totalOrderAmount);
    }

    /**
     * 输出订单分摊结果
     */
    public void displayOrderSplitInfo() {
        log.info("分摊后:");
        orderDetailList.forEach(e -> log.info(e.toString()));

        log.info("======================================================================");

        log.info("精简版:");
        orderDetailList.forEach(e -> log.info("{}:{}", e.getName(), new DecimalFormat("#.00").format(e.getPay())));
    }

}
